package com.vitalfit.annotation.support;

import com.vitalfit.annotation.LoginUser;
import com.vitalfit.model.vo.UserAuthentication;
import com.vitalfit.utils.TokenUtil;
import jakarta.servlet.ServletException;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    private static final String LOGIN_TOKEN_KEY = "Authorization";


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(UserAuthentication.class)
                && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(@NotNull MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest request,
                                  WebDataBinderFactory factory) throws Exception {
        String token = request.getHeader(LOGIN_TOKEN_KEY);
        if (token == null || token.isEmpty()) {
            // 处理token为空的情况，比如抛出自定义异常或返回null
            throw new ServletException("登录令牌为空");
        }

        try {
            Integer userId = TokenUtil.extractUserId(token);
            if (userId == null) {
                // 处理JWT解析失败的情况
                throw new ServletException("JWT解析失败");
            }
            return new UserAuthentication(token, userId);
        } catch (Exception e) {
            // 处理其他异常，比如JSON解析异常
            throw new ServletException("解析用户信息时出错", e);
        }
    }
}
